package cn.helper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.icu.util.Calendar;
import android.icu.util.GregorianCalendar;
import android.icu.util.TimeZone;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.BatteryManager;
import android.os.Build;
import android.util.Log;

import com.unity3d.player.UnityPlayer;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

public class SystemHelper {

    private final static String TAG = "BToolkit";

    /**
     * 当前设备 Android API 版本号(返回API版本号 29,30等)
     *
     * @return
     */
    public static int getAndroidSDKVersion() {
        Log.i(TAG, "getDeviceAPIVersion(): Build.VERSION.SDK_INT: " + Build.VERSION.SDK_INT);
        return Build.VERSION.SDK_INT;
    }

    /**
     * 获取电量
     * <uses-permission android:name="android.permission.BATTERY_STATS" />
     */
    @SuppressLint("NewApi")
    public static int getBatteryPercent() {
        int currentApiVersion = Build.VERSION.SDK_INT;
        if (currentApiVersion >= 21) {
            // 仅支持Andorid-21及以上版本
            BatteryManager batteryManager = (BatteryManager) UnityPlayer.currentActivity.getSystemService(Context.BATTERY_SERVICE);
            int percent = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);// 整数百分比（0-100）
            return percent;
        }
        return 0;
    }

    /**
     * 获取网络类型
     * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     */
    public static String getInternetType() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) UnityPlayer.currentActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
        @SuppressLint("MissingPermission") NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
            int type = mNetworkInfo.getType();
            if (type == ConnectivityManager.TYPE_WIFI) {
                return "Wifi";
            } else {
                return "Mobile";
            }
        }
        return "NoNet";
    }

    // 判断是否存在光传感器来判断是否为模拟器
    public static boolean isSimulator() {
        //通过判断是否有光传感器
        SensorManager sensorManager = (SensorManager) UnityPlayer.currentActivity.getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT) == null) {
            return true;
        }
        //通过检测系统属性
        if (Build.FINGERPRINT.startsWith("generic")
                || Build.FINGERPRINT.startsWith("unknown")
                || Build.MODEL.contains("google_sdk")
                || Build.MODEL.contains("Emulator")
                || Build.MODEL.contains("Android SDK built for x86")
                || Build.MANUFACTURER.contains("Genymotion")
                || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
                || "google_sdk".equals(Build.PRODUCT)){
            return true;
        }
        //通过检测硬件特征
        String board = Build.BOARD;
        String brand = Build.BRAND;
        String device = Build.DEVICE;
        String hardware = Build.HARDWARE;
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        if (hardware.equals("goldfish")) {
            return true;
        }
        if (board.equals("unknown") && brand.equals("generic") && device.equals("generic")
                && model.equals("sdk") && manufacturer.equals("unknown")) {
            return true;
        }
        if (board.equals("QC_Reference_Phone") || board.equals("MSM")) {
            return true;
        }
        if (manufacturer.contains("Genymotion")) {
            return true;
        }
        if (model.contains("Emulator")) {
            return true;
        }
        //通过检测虚拟机特征
        String[] known_emulators = {"goldfish", "ranchu", "vbox86"};
        for (String emulator : known_emulators) {
            if (Build.HARDWARE.contains(emulator)) {
                return true;
            }
        }
        //通过检测运行环境特征
        if(Build.PRODUCT.equals("sdk") || Build.PRODUCT.equals("google_sdk") || Build.PRODUCT.equals("sdk_x86") || Build.PRODUCT.equals("vbox86p")){
            return true;
        }
        //通过检测运行的应用程序列表
        PackageManager pm = UnityPlayer.currentActivity.getPackageManager();
        List<ApplicationInfo> apps = pm.getInstalledApplications(PackageManager.GET_META_DATA);
        for (ApplicationInfo app : apps) {
            if ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                // 非系统应用
                if (app.packageName.contains("com.bluestacks")
                        || app.packageName.contains("com.bignox.app")
                        || app.packageName.contains("com.androvm")
                        || app.packageName.contains("com.genymotion")) {
                    return true;
                }
            }
        }
        return false;
    }

    // 无需权限获取唯一UUID识别码
    public static String getDeviceID() {
        String serial = "serial";
        String m_szDevIDShort = "LT" + Build.BOARD + Build.BRAND + Build.DEVICE + Build.MANUFACTURER + Build.PRODUCT;
        //使用硬件信息拼凑出来的号码
        String s = new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        return s;
    }

    // 获取系统时区ID（如：Asia/Shanghai）
    public static String getSysTimeZoneID() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            TimeZone timeZone = TimeZone.getDefault();
            return timeZone.getID();
        }
        return null;
    }

    // 获取系统时区Name（如：GMT+08:00）
    public static String getSysTimeZoneName() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            TimeZone tz = TimeZone.getDefault();
            Calendar cal = GregorianCalendar.getInstance(tz);
            int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
            String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
            return "GMT" + (offsetInMillis >= 0 ? "+" : "-") + offset;
        }
        return null;
    }

    // 根据包名获取已安装App的签名信息
    public static String getAppSignInfoByPackName(String packName) {
        PackageManager pm = UnityPlayer.currentActivity.getPackageManager();
        List<PackageInfo> apps = pm.getInstalledPackages(PackageManager.GET_SIGNATURES);
        Iterator<PackageInfo> it = apps.iterator();
        while(it.hasNext()){
            PackageInfo info = it.next();
            if(info.packageName.equals(packName)){
                Signature sign = info.signatures[0];
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("MD5", getSignatureByteString(sign, "MD5"));
                    jsonObject.put("SHA1", getSignatureByteString(sign, "SHA1"));
                    jsonObject.put("SHA256", getSignatureByteString(sign, "SHA256"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return jsonObject.toString();
            }
        }
        return null;
    }
    private static String getSignatureByteString(Signature sig, String type) {
        byte[] hexBytes = sig.toByteArray();
        String fingerprint = "error!";
        try {
            MessageDigest digest = MessageDigest.getInstance(type);
            if (digest != null) {
                byte[] digestBytes = digest.digest(hexBytes);
                StringBuilder sb = new StringBuilder();
                for (byte digestByte : digestBytes) {
                    sb.append(((Integer.toHexString((digestByte & 0xFF) | 0x100)).substring(1, 3)).toUpperCase());
                    sb.append(":");
                }
                fingerprint = sb.substring(0, sb.length() - 1);
            }
        } catch (Exception e) {
            Log.e(TAG, "getSignatureByteString failed", e);
        }

        return fingerprint;
    }

    /**
     * 安装Apk（三步）
     * 1、配置权限<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
     * 2、配置provider
     * <provider
     *     android:name="android.support.v4.content.FileProvider"
     *     android:authorities="${applicationId}.fileProvider"
     *     android:exported="false"
     *     android:grantUriPermissions="true">
     *     <meta-data
     *     	android:name="android.support.FILE_PROVIDER_PATHS"
     *         android:resource="@xml/provider_paths" />
     * </provider>
     * 3、创建xml文件配置一次性临时存储位置，并把xml文件名赋值给provider,然后该xml导出aar包给Unity使用（provider_xml.aar已导出到Unity目录）
     * 教程：https://blog.csdn.net/lanlangaogao/article/details/125291127
     public static void installApk(String path) {
         File file = new File(path);
         Intent intent = new Intent(Intent.ACTION_VIEW);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         Activity context = UnityPlayer.currentActivity;
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
         //注意第二个参数，要保持和manifest中android:authorities的值相同
         Uri uri = FileProvider.getUriForFile(context,context.getPackageName() + ".fileProvider", file);
         intent.setDataAndType(uri, "application/vnd.android.package-archive");
         } else {
         intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
         }
         try {
         context.startActivity(intent);
         } catch (Exception e) {
         e.printStackTrace();
         }
     }
     */
}